/**
 * 系统退款单管理相关js文件
 */
var sysRefundList = {};
var $sysRefundTable = null;
sysRefundList.operation = {};

var $contentIframe = null;

// 页面初始化
$(function() {
    // 店铺列表初始化
    sysRefundList.initShopList();
    
    sysRefundList.initSysRefundTable();

    // 按钮绑定
    $("#btnQuickSearch").unbind("click").bind("click", sysRefundList.queryTableData);
    $("#navTabBar li").find("a[data-toggle='tab']").unbind("click").click(function() {
        $("#quickSearch").data("queryStatus", $(this).attr("id"));
        sysRefundList.queryTableData();
    });
    
    // 快速查询回车
    $('#quickSearch').keydown(function(e){
        if (e.keyCode == 13&&$('#btnQuickSearch').is(":visible")) {
            
            $('#btnQuickSearch').click();
        }
    });
    

    // 高级搜索绑定
    sysRefundList.initAdvSearch();
    
    
    // 下载按钮功能绑定
    sysRefundList.initDownloadBtn();
    
//    var MutationObserver = window.MutationObserver ||
//        window.WebKitMutationObserver ||
//        window.MozMutationObserver;
//
//    var mutationObserverSupport = !!MutationObserver;
//    
//    if(mutationObserverSupport){
//        var observer = new MutationObserver(function(records){
//            var width = $("div.tab-content").css("width");
//            var iframeDom = $("div.tab-content").find("iframe:visible");
//            if(iframeDom.length>0){
//                iframeDom.eq(0).css("width",(width-30)+"px");
//            }
//        });    
//        
//        var observerContent = $("div.tab-content")[0];
//        var options = {'attributes':true,'subtree':true,'attributesFilter':['style']};
//        observer.observe(observerContent,options);
//    }
    
    $(window.top.window).resize(function(){
        var swidth = $("div.tab-content").width()-30;
        var iframeDom = $("div.tab-content").find("iframe:visible");
        ;
        if(iframeDom.length>0){
            iframeDom.eq(0).width(Number(swidth));
        }
    });
});

// 初始化项目列表控件
sysRefundList.initShopList = function(){
    var prjShopList = sysRefundList.operation.getPrjShopList();
    var optionTemplate = "";
    var tempItem = "";
    for(var i=0,j=prjShopList.length;i<j;i++){
        tempItem = prjShopList[i];
        optionTemplate = '<option value="'+tempItem.shopId+'">'+tempItem.shopName+'</option>';
        $(".selectShop").append($(optionTemplate));
    }
};

sysRefundList.operation.getPrjShopList = function(){
    var returnData = {};
    $.ajax({
        type : "GET",
        url : "/shop/unpagedShopList.action",
        contentType : "application/json;charset=utf-8",
        dataType : "json",
        //async : false,
        success : function(data) {
            if (data.result == "success") {
                returnData = data.data;
            } else {
                window.top.window.showModalAlert("项目店铺获取失败，原因是："+data.message);
            }
        },
        error : function(XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                window.top.window.showModalAlert("项目店铺获取失败");
            }
        }
    });
    return returnData;
}

sysRefundList.initDownloadBtn = function(){
    sysRefundList.initDownloadBtnClickEvent("manualDownloadEcRefund","manualRefund");
    sysRefundList.initDownloadBtnClickEvent("manualDownloadShopRefund","manualUser");
    sysRefundList.initDownloadBtnClickEvent("manualDownloadOrderRefund","manualOrder");
    
    $("#doDownloadEcRefund").bind("click",function(){
        sysRefundList.downloadByEcRefundCode(this);
    });
    $("#doDownloadBuyerRefund").bind("click",function(){
        sysRefundList.downloadByCustomerId(this);
    });
    $("#doDownloadOrder").bind("click",function(){
    		sysRefundList.downloadByOrderCode(this);
    });
};

sysRefundList.initDownloadBtnClickEvent = function(domId,modalId){
    //  初始化弹出框中的select控件
    $(".selectpickerModal").val("");
    
    var validator = $("#"+modalId).find("form").validate({
        debug : true,
        ignore : "",
        errorPlacement : function(error, element) {
            error.insertAfter(element);
        }
    });
    
    $("#"+domId).bind("click",function(){
        var downloadDialog = window.top.window.borrowCustomModalDialog($("#"+modalId));
        validator.resetForm();
        $(downloadDialog).find("form").eq(0).find("select,input").val("");
        downloadDialog.on('hide.bs.modal', function() {
            // 父窗体归还本页的编辑对话框
            window.top.window.returnCustomModalDialog();
        });
        
        downloadDialog.modal({
            show : true,
            backdrop : 'static'
        });
    });
    
    
};

// 根据客户ID手动下载退款单
sysRefundList.downloadByCustomerId = function(btnElement){
    
    var $formElement = $(btnElement).parents("form").eq(0);
    if($formElement.valid()){
        var shopId = $("#shopSelect4UserId",$formElement).val();
        var customerId = encodeURI($("#customerId",$formElement).val());
        sysRefundList.operation.manualDownloadByCustomerId(shopId,customerId);
    }
};
// 根据客户ID手动下载退款单
sysRefundList.downloadByOrderCode = function(btnElement){
	
	var $formElement = $(btnElement).parents("form").eq(0);
	if($formElement.valid()){
		var shopId = $("#shopSelect4OrderCode",$formElement).val();
		var orderCode = encodeURI($("#orderCode",$formElement).val());
		sysRefundList.operation.manualDownloadByOrderCode(shopId,orderCode);
	}
};

// 根据平台退款单编号手动下载退款单
sysRefundList.downloadByEcRefundCode = function(btnElement){
    // 重置内容
    var $formElement = $(btnElement).parents("form").eq(0);
    if($formElement.valid()){
        var shopId = $("#shopSelect4EcRefundCode",$formElement).val();
        var refundCode = encodeURI($("#refundCode",$formElement).val());
        sysRefundList.operation.manualDownloadByEcRefundCode(shopId,refundCode);
    }
};


/*
 * 手动下载退款单:
 * @param shopId 店铺ID
 * @param customerId 客户ID
 */ 
sysRefundList.operation.manualDownloadByCustomerId=function(shopId,customerId){
	
    $.ajax({
        type : "GET",
        url : "/sysRefundManager/manualGenerateSysRefundByCustomerId.action",
        contentType : "application/json;charset=utf-8",
        data : {
            "shopId" : shopId
            ,"customerId" : customerId
        },
        dataType : "json",
        async : false,
        success : function(data) {
            if (data.result == "success") {
                window.top.window.showScoMessage('ok', data.msg);
                $('#manualUser', window.top.document).find("#moduleCloseBtn").click();
                sysRefundList.queryTableData();
            } else {
                window.top.window.showModalAlert(data.msg);
            }
        },
        error : function(XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                window.top.window.showModalAlert(result.errorObject.errorText);
            }
        }
    });
};

/*
 * 根据退款单号手动下载退款单:
 * @param shopId 店铺ID
 * @param ecRefundCode 平台退款单号
 */ 
sysRefundList.operation.manualDownloadByEcRefundCode=function(shopId,ecRefundCode){
	
	$.ajax({
		type : "GET",
		url : "/sysRefundManager/manualGenerateSysRefundByEcRefundCode.action",
		contentType : "application/json;charset=utf-8",
		data : {
			"shopId" : shopId
			,"ecRefundCode" : ecRefundCode
		},
		dataType : "json",
		async : false,
		success : function(data) {
			if (data.result == "success") {
				window.top.window.showScoMessage('ok', data.msg);
				$('#manualRefund', window.top.document).find("#moduleCloseBtn").click();
				sysRefundList.queryTableData();
			} else {
				window.top.window.showModalAlert(data.msg);
			}
		},
		error : function(XMLHttpRequest, textStatus) {
			if (XMLHttpRequest.status == 500) {
				var result = eval("(" + XMLHttpRequest.responseText + ")");
				window.top.window.showModalAlert(result.errorObject.errorText);
			}
		}
	});
};

/*
 * 根据订单号手动下载退款单:
 * @param shopId 店铺ID
 * @param orderCode 订单号
 */ 
sysRefundList.operation.manualDownloadByOrderCode=function(shopId,orderCode){
	
	$.ajax({
		type : "GET",
		url : "/sysRefundManager/manualGenerateSysRefundByOrderCode.action",
		contentType : "application/json;charset=utf-8",
		data : {
			"shopId" : shopId
			,"orderCode" : orderCode
		},
		dataType : "json",
		async : false,
		success : function(data) {
			if (data.result == "success") {
				window.top.window.showScoMessage('ok', data.msg);
				$('#manualOrder', window.top.document).find("#moduleCloseBtn").click();
				sysRefundList.queryTableData();
			} else {
				window.top.window.showModalAlert(data.msg);
			}
		},
		error : function(XMLHttpRequest, textStatus) {
			if (XMLHttpRequest.status == 500) {
				var result = eval("(" + XMLHttpRequest.responseText + ")");
				window.top.window.showModalAlert(result.errorObject.errorText);
			}
		}
	});
};

// 初始化系统退款单列表
sysRefundList.initSysRefundTable = function() {
    $sysRefundTable = $("#sysRefundTable")
            .DataTable(
                    {
                        "processing" : true,
                        "serverSide" : true,
                        "lengthMenu" : [ [ 10, 25, 50, 100, 500, 1000 ], [ 10, 25, 50, 100,500,1000 ] ],
                        "dom" : '<"bottom"rtflp>',
                        "searching" : false,
                        "scrollX" : "100%",
                        "scrollY" : "410px",
                        "scrollCollapse": false,
                        "destroy" : true,
                        "pagingType" : "full_numbers",
                        "deferRender" : true,
                        "ajax" : {
                            "url" : "/sysRefundManager/sysRefundList.action",
                            "type" : "get",
                            "data" : function(d) {
                                    d.formJson = $("#advSearchPanel").data("queryData");
                                    d.quickSearch = encodeURI($("#quickSearch").val());
                                    d.queryStatus = encodeURI($("#quickSearch").data("queryStatus") ? $("#quickSearch").data("queryStatus")
                                            : $("#navTabBar").find("li.active").find("a:eq(0)").attr("id"));
                            }
                        },
                        "columns" : [ {
                            "data" : "sonShow"
                        }, {
                            "data" : "refundChannel",
                            "render" : function(data) {
                                var returnValue = "";
                                if (data == "online") {
                                    returnValue = '线上';
                                } else {
                                    returnValue = '线下';
                                }
                                return returnValue;
                            },
                            "orderable":false
                        }, {
                            "data" : "refundCode",
                            "orderable":false
                        }, {
                            "data" : "shopName",
                            "orderable":false
                        }
                        , {
                            "data" : "returnDiff",
                            "render" : function(data) {
                                var returnValue = "";
                                if (data == "y") {
                                    returnValue = '<span class="badge badge-orange"> </span>';
                                } else {
                                    returnValue = '-';
                                }
                                return returnValue;
                            }
                        }, {
                            "data" : "refundPhase",
                            "render" : function(data) {
                                var returnValue = "";
                                if (data == "onsale") {
                                    returnValue = "售中退款";
                                } else if (data == "aftersale") {
                                    returnValue = "售后退款";
                                }
                                return returnValue;
                            }
                        }, {
                            "data" : "refundSourceOrderCode",
                        }, {
                            "data" : "ecTradeCode",
                        }, {
                            "data" : "ecRefundCode"
                        }, {
                            "data" : "createTime"
                        }, {
                            "data" : "paidDate"
                        }, {
                            "data" : "refundReason",
                            "orderable":false,
                            "render" : function(data) {
                                
                                returnValue = "-";
                                if(!!data){
                                    returnValue = data;
                                }
                                return returnValue;
                            }
                        }, {
                            "data" : "refundReasonName"
                        }, {
                            "data" : "buyerRemark"
                        }, {
                            "data" : "ecOrderStatus",
                            "render" : function(data) {
                                var returnValue = "-";
                                if (data == "EC_WAIT_BUYER_PAY") {
                                    returnValue = "等待买家付款";
                                } else if (data == "EC_WAIT_SELLER_SEND") {
                                    returnValue = "等待卖家发货";
                                } else if (data == "EC_TRADE_PARTIALLY_SEND") {
                                    returnValue = "交易部分发货";
                                } else if (data == "EC_TRADE_ALL_SEND") {
                                    returnValue = "交易全部发货";
                                } else if (data == "EC_TRADE_FINISHED") {
                                    returnValue = "交易成功";
                                } else if (data == "EC_TRADE_CANCELED") {
                                    returnValue = "交易取消";
                                }
                                return returnValue;
                            }
                        }, {
                            "data" : "orderStatus",
                            "render" : function(data) {
                                var returnValue = "-";
                                if (data == "a") {
                                    returnValue = "待审核";
                                } else if (data == "i") {
                                    returnValue = "待分派";
                                } else if (data == "k") {
                                    returnValue = "发货中";
                                } else if (data == "r") {
                                    returnValue = "已发货";
                                } else if (data == "z") {
                                    returnValue = "已完成";
                                }
                                return returnValue;
                            }
                        }, {
                            "data" : "refundStatus",
                            "render" : function(data) {
                                var returnValue = "-";
                                if (data == "a") {
                                    returnValue = "登记";
                                } else if (data == "c") {
                                    returnValue = "登记";
                                } else if (data == "e") {
                                    returnValue = "已审核";
                                } else if (data == "y") {
                                    returnValue = "已退款";
                                } else if (data == "d") {
                                    returnValue = "登记";
                                } else if (data == "b") {
                                    returnValue = "登记";
                                }
                                return returnValue;
                            }
                        }, {
                            "data" : "hasGoodReturn",
                            "render" : function(data) {
                                var returnValue = "-";
                                if (data == "y") {
                                    returnValue = "买家需要退货";
                                } else if (data == "n") {
                                    returnValue = "买家不退货";
                                }
                                return returnValue;
                            }

                        }, {
                            "data" : "operation"
                        } ],
                        "columnDefs": [
                            {"className": "truncate-text tooltip-column-detail", "targets":[1]},
                            {"className": "truncate-text tooltip-column-detail", "targets":[2]},
                            {"className": "truncate-text tooltip-column-detail", "targets":[3]},
                            {"className": "truncate-text tooltip-column-detail", "targets":[4]},
                            {"className": "truncate-text tooltip-column-detail", "targets":[5]},
                            {"className": "truncate-text tooltip-column-detail", "targets":[6]},
                            {"className": "truncate-text tooltip-column-detail", "targets":[7]},
                            {"className": "truncate-text tooltip-column-detail", "targets":[8]},
                            {"className": "truncate-text tooltip-column-detail", "targets":[9]},
                            {"className": "truncate-text tooltip-column-detail", "targets":[10]},
                            {"className": "truncate-text tooltip-column-detail", "targets":[11]},
                            {"className": "truncate-text tooltip-column-detail", "targets":[12]},
                            {"className": "truncate-text tooltip-column-detail", "targets":[13]},
                            {"className": "truncate-text tooltip-column-detail", "targets":[14]},
                            {"className": "truncate-text tooltip-column-detail", "targets":[15]},
                            {"className": "truncate-text tooltip-column-detail", "targets":[16]},
                            {"className": "truncate-text tooltip-column-detail", "targets":[16]}
                            
                        ]
                    })
            .on(
                    'draw.dt',
                    function() {
                    	//解决因滚动条导致的列对不齐问题
           	         	$(".dataTables_scrollBody").css("overflow-y","overlay");
                        // 以下注释部分是用于固定列调整样式用的，需要固定列时打开下面代码
                        setTimeout(function() {
                            var rightWidth = $('#sysRefundTable_wrapper').find("div.DTFC_RightBodyLiner").width();
                            var leftWidth = $('#sysRefundTable_wrapper').find("div.DTFC_LeftBodyLiner").width();

                            $('#sysRefundTable_wrapper').find("div.DTFC_LeftBodyLiner").width(leftWidth + 4);
                            $('#sysRefundTable_wrapper').find("div.DTFC_RightBodyLiner").width(rightWidth + 4);
                        }, 1);
                        $("table").find("th.sorting_asc").removeClass("sorting_asc");
                        // 表格绘制完成后的回调事件
                        $('#sysRefundTable td .fa-chevron-down')
                                .on(
                                        'click',
                                        function(event) {
                                            event.stopPropagation();

                                            var tr = $(this).closest("tr");
                                            row = $sysRefundTable.row(tr);

                                            if (row.child.isShown()) {
                                                row.child.hide();
                                                tr.removeClass('shown');
                                                $(this).removeClass('fa-chevron-up');
                                                $(this).addClass('fa-chevron-down');
                                            } else {
                                                // 关闭其他
                                                $('#sysRefundTable tbody tr').each(function() {
                                                    if ($(this).attr("role") == "row") {
                                                        $sysRefundTable.row($(this)).child.hide();
                                                    }
                                                });

                                                $('.fa-chevron-up', $('#sysRefundTable tbody')).addClass('fa-chevron-down');
                                                $('.fa-chevron-down', $('#sysRefundTable tbody')).removeClass('fa-chevron-up');

                                                var refundId = row.data().refundId;
                                                var ifmSrc = "/views/aftersale/sysrefund/sysRefundDetail.html?refundId=" + refundId;
                                                var swidth = $("div.tab-content").width() - 30;
//                                                var swidth = "100%";
                                                var sheight = "380";
                                                var temp = '<iframe myid="" tab="" shopType="" id="contentFrame1" name="contentFrame" style="width:'+swidth+'px" frameborder="0" scrolling="auto" src="'
                                                        + ifmSrc + '" height="'+(sheight-20)+'"></iframe>';
                                                row.child(temp).show();
                                                tr.addClass("shown");
                                                
//                                                tr.next().css("height",sheight);
                                                
                                                $contentIframe = tr.find("iframe").eq(0);
                                                
                                                $(this).addClass('fa-chevron-up');
                                                $(this).removeClass('fa-chevron-down');
                                            }
                                            return false;
                                        });
                        // 更新列表上TAB状态的数值
                        $.ajax({
                            type : "GET",
                            url : "/sysRefundManager/queryStateCount.action",
                            contentType : "application/json;charset=utf-8",
                            data:{
                                formJson : $("#advSearchPanel").data("queryData"),
                                quickSearch : encodeURI($("#quickSearch").val())
                            },
                            dataType : "json",
                            async : false,
                            success : function(data) {
                                if (data.result == "success") {
                                    for ( var index in data.data) {
                                        $("#" + data.data[index].state + "_count").html(data.data[index].num);
                                    }
                                } else {
                                    window.top.window.showModalAlert(data.msg);
                                }
                            },
                            error : function(XMLHttpRequest, textStatus) {
                                if (XMLHttpRequest.status == 500) {
                                    var result = eval("(" + XMLHttpRequest.responseText + ")");
                                    window.top.window.showModalAlert(result.errorObject.errorText);
                                }
                            }
                        });
                    });
    
    // 文字过长截断显示悬浮框
    $("#sysRefundTable").tooltip({
        selector: ".tooltip-column-detail",
        container: "body",
        title: function() {
            if ($(this)[0].scrollWidth > $(this).outerWidth()) {
                return $(this).text();
            }
        }
    });
};

sysRefundList.cancelAuthen = function(btnObject) {
    var refundId = $(btnObject).attr("refundid");
    if (!!refundId) {
        window.top.window.showModalConfirm("确定要取消审核吗", function() {
            sysRefundList.operation.cancelAuthen(refundId);
        });
    }
}

// 审核按钮点击事件
sysRefundList.authen = function(btnObject) {
    var refundId = $(btnObject).attr("refundid");
    if (!!refundId) {
        sysRefundList.operation.authen(refundId);
    }
};

// 强制审核按钮点击事件
sysRefundList.forceAuthen = function(btnObject) {
    var refundId = $(btnObject).attr("refundid");
    if (!!refundId) {
        sysRefundList.operation.forceAuthenValid(refundId);
    }
};

// 查询数据
sysRefundList.queryTableData = function() {
    var queryData = $("#advSearchPanel").data("queryData");
    if (null == $sysRefundTable) {
        sysRefundList.initSysRefundTable();
    } else {
        var optionData = $sysRefundTable.settings()[0].ajax.data;
        if (optionData.formJson) {
            optionData.formJson = encodeURI(JSON.stringify($.extend(true, {}, $.parseJSON(optionData.formJson), $.parseJSON(queryData))));
        }
        optionData.quickSearch = encodeURI($("#quickSearch").val());
        optionData.queryStatus = encodeURI($("#quickSearch").data("queryStatus"));

        $sysRefundTable.settings()[0].ajax.data = optionData;
        $sysRefundTable.ajax.reload();
    }
};

/*
 * 刷新系统退款单列表
 */
sysRefundList.refresh = function() {
    $('#quickSearch').val("");
    quickSearch = "";
    $("#advSearchReset").click();
    searchCondition = {};
    if (!$("#advSearchPanel").is(":hidden")){
        $("#btnAdvSearch").click();   
    }  
    sysRefundList.queryTableData();
};
sysRefundList.refund = function(btnObject) {
    var refundId = $(btnObject).attr("refundid");
    if (!!refundId) {
        sysRefundList.operation.refundValid(refundId);
    }
};

/*
 * 导出退款单列表
 */
sysRefundList.exportSysRefund = function() {

};

sysRefundList.resetAdvSearch = function(){
    var formObj = $("#frmAdvSearch");
    $("input",formObj).val("");
    $("select.selectpicker",formObj).selectpicker("val","");
    
    $("#dateType",formObj).selectpicker("val","");
    $("#returnDiff",formObj).selectpicker("val","");
    $("#source",formObj).selectpicker("val","");
    $("#returnCondition",formObj).selectpicker("val","");

    var searchCondition = { // 高级检索
            orderCode : "", // 订单编号
            shopId : "", // 店铺名称
            source : "", // 来源
            dateType : "", // 日期类型
            dateStart : "", // 开始日期
            dateEnd : "", // 截止日期
            ecItemCode : "", // 平台商品编号
            ecSkuCode : "", // 平台退格编码
            skuCode : "",// 规格商家编码
            refundChannel:"",//退款单类型
            queryDateStart : "",// 查询时间开始
            queryDateEnd : ""// 查询时间结束
            ,returnDiff : ""// 退货差异

        };
    sysRefundList.setdaterange();
    $("#advSearchPanel").data("queryData",searchCondition);
}

sysRefundList.initAdvSearch = function() {
    $(".selectpicker").selectpicker();
    
    $("#advSearchReset").bind("click",sysRefundList.resetAdvSearch);
    
 // 日期区间选择控件初始化
    $('.reportrange').daterangepicker(
            {
                ranges : {
                    '昨天' : [ moment().add('days', -1).startOf('day'),
                            moment().add('days', -1).endOf('day') ],
                    '过去7天' : [ moment().add('days', -7).startOf('day'),
                            moment().add('days',-1).endOf('day') ],
                    '过去30天' : [ moment().add('days', -30).startOf('day'),
                            moment().add('days', -1).endOf('day') ],
                    '本月' : [ moment().startOf('month').startOf('day'),
                            moment().endOf('month').endOf('day') ],
                    '上月' : [
                            moment().add('month', -1).startOf('month')
                                    .startOf('day'),
                            moment().add('month', -1).endOf('month').endOf(
                                    'day') ]
                },
                timePicker : false,
                maxDate : moment().startOf('day').format(
                        'YYYY-MM-DD'),
                opens : 'right', // 日期选择框的弹出位置
                buttonClasses : [ 'btn btn-default' ],
                applyClass : 'btn-small btn-primary blue',
                endDate : moment().endOf('day').format('YYYY-MM-DD'),
                startDate : moment().add('days', -6).startOf('day').format('YYYY-MM-DD'),
                cancelClass : 'btn-small',
                format : 'YYYY-MM-DD', // 控件中from和to 显示的日期格式
                separator : ' 到 ',
                locale : {
                    applyLabel : '确定',
                    cancelLabel : '取消',
                    fromLabel : '起始时间',
                    toLabel : '结束时间',
                    customRangeLabel : '自定义',
                    daysOfWeek : [ '日', '一', '二', '三', '四', '五', '六' ],
                    monthNames : [ '一月', '二月', '三月', '四月', '五月', '六月',
                            '七月', '八月', '九月', '十月', '十一月', '十二月' ],
                    firstDay : 1
                }
            },sysRefundList.setdaterange);
    
    btnAdvSearchflg = false;
    sysRefundList.setdaterange();

    // 高级搜索
    $("#btnAdvSearch").click(function() {
        btnAdvSearchflg = true;
        if ($("#advSearchPanel").is(":hidden")) {
            $("#btnQuickSearch").hide();
            $("#advSearchPanel").show();
            $(this).children("i:eq(0)").removeClass("fa-angle-double-down");
            $(this).children("i:eq(0)").addClass("fa-angle-double-up");
        } else {
            sysRefundList.resetAdvSearch();
            $("#advSearchPanel").hide();
            $("#btnQuickSearch").show();
            $(this).children("i:eq(0)").removeClass("fa-angle-double-up");
            $(this).children("i:eq(0)").addClass("fa-angle-double-down");
        }
    });

    $("#advSearchPanel").click(function() {
        btnAdvSearchflg = true;
    })

    // 高级搜索“提交”按钮点击
    $("#advSearchSubmit").click(function(e) {
        var queryDateStart = $('#datestart').val()?$('#datestart').val()+" 00:00:00":"";
        var queryDateEnd = $('#dateend').val()?$('#dateend').val()+" 23:59:59":"";
        if(!!$('#datestart').val()||!!$('#dateend').val()){
            if(!$('#dateType').val()){
                window.top.window.showModalAlert("请选择日期类型");     
                return;
            }
        }
        var searchCondition = { // 高级检索
            orderCode : $('#orderCode').val(), // 订单编号
            shopId : $('#shopName').val(), // 店铺名称
            source : $('#source').val(), // 来源
            dateType : $('#dateType').val(), // 日期类型
            dateStart : $('#dateStart').val(), // 开始日期
            dateEnd : $('#dateEnd').val(), // 截止日期
            ecItemCode : $('#ecItemCode').val(), // 平台商品编号
            ecSkuCode : $('#ecSkuCode').val(), // 平台退格编码
            skuCode : $('#skuCode').val(),
            refundChannel:$('#returnCondition').val(),//退款单类型
            queryDateStart : queryDateStart,
            queryDateEnd : queryDateEnd
            ,returnDiff:$("#returnDiff").val()  //退货差异
        };

        $("#advSearchPanel").data("queryData", encodeURI(JSON.stringify(searchCondition)));
        
        sysRefundList.queryTableData();
    });
};

// 设置时间区间，用于区间的初始化和区间控件选择后的回调
sysRefundList.setdaterange = function(start, end) {
    if(!start||!end){
        $('.reportrange span').html("请选择时间区间");
        $('input[name="datestart"]').val("");
        $('input[name="dateend"]').val("");
    }else{
        $('.reportrange span').html(start.format('YYYY-MM-DD') + ' - ' + end.format('YYYY-MM-DD'));
        $('input[name="datestart"]').val(start.format("YYYY-MM-DD"));
        $('input[name="dateend"]').val(end.format("YYYY-MM-DD"));
    }
    
};

// 废弃按钮操作
sysRefundList.operationDelete = function(btnObj) {
    if (btnObj) {
        var refundId = $(btnObj).attr("refundId");
        if (!!refundId) {
            window.top.window.showModalConfirm("确定要废弃吗", function() {
                sysRefundList.operation.Delete(refundId);
            });
        }

    }
};
// 修改退款单
sysRefundList.operationEdit = function(btnObj) {
    if (btnObj) {
        var sysRefundId = $(btnObj).attr("refundId");
        if (!!sysRefundId) {
            var iframeSrc = "./views/aftersale/sysrefund/sysRefundEdit.html?sysRefundId=" + sysRefundId;
            // 新增的界面样例
            // var iframeSrc =
            // "./views/aftersale/sysrefund/sysRefundEdit.html?sysOrderId=3ffdaca379984618bab6412fef8a9b1c";
            $("#ifmSysRefundDetail").attr("src", iframeSrc);
            $("#btnSave").unbind("click").bind(
                    "click",
                    function() {
                        // 调用子页面的保存方法
                        window.top.frames["ifmSysRefundDetail"].window.sysRefundEdit
                                .saveSysRefund(window.top.frames["ifmSysRefundDetail"].contentWindow);
                        sysRefundList.queryTableData();
                    });
            var sysRefundDetailDialog = window.top.window.borrowCustomModalDialog($("#modalSysRefundDetail"));
            sysRefundDetailDialog.on('hide.bs.modal', function() {
                // 父窗体归还本页的编辑对话框
                window.top.window.returnCustomModalDialog();
            });
            sysRefundDetailDialog.modal({
                show : true,
                backdrop : 'static'
            });
        }
    }
};

// 废弃系统退款单
sysRefundList.operation.Delete = function(sysRefundIds) {
	var loading = window.top.window.getIndexBusyOverlay();
    $.ajax({
        type : "GET",
        url : "/sysRefundManager/cancelSysRefund.action",
        contentType : "application/json;charset=utf-8",
        data : {
            "refundIds" : sysRefundIds
        },
        dataType : "json",
//        async : false,
        beforeSend:function(){
            if(loading) {
            	loading.settext("正在处理中，请稍后...");
            }
        },
        success : function(data) {
        	loading.remove();
            if (data.result == "success") {
                window.top.window.showScoMessage('ok', data.msg);
                sysRefundList.queryTableData();
            } else {
                window.top.window.showModalAlert(data.msg);
            }
        },
        error : function(XMLHttpRequest, textStatus) {
        	loading.remove();
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                window.top.window.showModalAlert(result.errorObject.errorText);
            }
        }
    });
};

// 退款
sysRefundList.operation.refundValid = function(sysRefundId) {
	var loading = window.top.window.getIndexBusyOverlay();
    $.ajax({
        type : "GET",
        url : "/sysRefundManager/doRefundValid.action",
        contentType : "application/json;charset=utf-8",
        data : {
            "refundId" : sysRefundId
        },
        dataType : "json",
//        async : false,
        beforeSend:function(){
            if(loading) {
            	loading.settext("正在处理中，请稍后...");
            }
        },
        success : function(data) {
        	loading.remove();
            if (data.result == "success") {
                window.top.window.showModalConfirm(data.msg + " 确定要退款吗?", function() {
                    sysRefundList.operation.refund(sysRefundId);
                });
            } else {
                window.top.window.showModalAlert(data.msg);
            }
        },
        error : function(XMLHttpRequest, textStatus) {
        	loading.remove();
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                window.top.window.showModalAlert(result.errorObject.errorText);
            }
        }
    });
};

// 执行退款
sysRefundList.operation.refund = function(sysRefundIds) {
	var loading = window.top.window.getIndexBusyOverlay();
    $.ajax({
        type : "GET",
        url : "/sysRefundManager/doRefund.action",
        contentType : "application/json;charset=utf-8",
        data : {
            "refundIds" : sysRefundIds
        },
        dataType : "json",
//        async : false,
        beforeSend:function(){
            if(loading) {
            	loading.settext("正在处理中，请稍后...");
            }
        },
        success : function(data) {
        	loading.remove();
            if (data.result == "success") {
                window.top.window.showScoMessage('ok', data.msg);
                sysRefundList.queryTableData();
            } else {
                window.top.window.showModalAlert(data.msg);
            }
        },
        error : function(XMLHttpRequest, textStatus) {
        	loading.remove();
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                window.top.window.showModalAlert(result.errorObject.errorText);
            }
        }
    });
};

// 取消审核
sysRefundList.operation.cancelAuthen = function(sysRefundIds) {
	var loading = window.top.window.getIndexBusyOverlay();
    $.ajax({
        type : "GET",
        url : "/sysRefundManager/cancelAuthenSysRefund.action",
        contentType : "application/json;charset=utf-8",
        data : {
            "refundIds" : sysRefundIds
        },
        dataType : "json",
//        async : false,
        beforeSend:function(){
            if(loading) {
            	loading.settext("正在处理中，请稍后...");
            }
        },
        success : function(data) {
        	loading.remove();
            if (data.result == "success") {
                window.top.window.showScoMessage('ok', data.msg);
                sysRefundList.queryTableData();
            } else {
                window.top.window.showModalAlert(data.msg);
            }
        },
        error : function(XMLHttpRequest, textStatus) {
        	loading.remove();
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                window.top.window.showModalAlert(result.errorObject.errorText);
            }
        }
    });
};

// 审核
sysRefundList.operation.authen = function(sysRefundIds) {
	var loading = window.top.window.getIndexBusyOverlay();
    $.ajax({
        type : "GET",
        url : "/sysRefundManager/apprSysRefund.action",
        contentType : "application/json;charset=utf-8",
        data : {
            "refundIds" : sysRefundIds
        },
        dataType : "json",
//        async : false,
        beforeSend:function(){
            if(loading) {
            	loading.settext("正在处理中，请稍后...");
            }
        },
        success : function(data) {
        	loading.remove();
            if (data.result == "success") {
                if (data.detail.length > 0) {
                    var apprResult = data.detail[0];    // 目前只审核单条退款单，所以取第一条
                    window.top.window.showScoMessage('ok', data.msg);
                    sysRefundList.dealWithMessage(apprResult);
                }
            } else {
                window.top.window.showModalAlert(data.msg);
            }
        },
        error : function(XMLHttpRequest, textStatus) {
        	loading.remove();
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                window.top.window.showModalAlert(result.errorObject.errorText);
            }
        }
    });
};

// 强制审核校验
sysRefundList.operation.forceAuthenValid = function(sysRefundId) {
	var loading = window.top.window.getIndexBusyOverlay();
    $.ajax({
        type : "GET",
        url : "/sysRefundManager/forceApprSysRefundValid.action",
        contentType : "application/json;charset=utf-8",
        data : {
            "refundId" : sysRefundId
        },
        dataType : "json",
//        async : false,
        beforeSend:function(){
            if(loading) {
            	loading.settext("正在处理中，请稍后...");
            }
        },
        success : function(data) {
        	loading.remove();
            if (data.result == "success") {
                if (!!data.message) {
                    var apprResult = data.message;
                    window.top.window.showScoMessage('ok', data.msg);
                    sysRefundList.dealWithMessage(apprResult);
                }
            } else {
                window.top.window.showModalAlert(data.msg);
            }
        },
        error : function(XMLHttpRequest, textStatus) {
        	loading.remove();
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                window.top.window.showModalAlert(result.errorObject.errorText);
            }
        }
    });
};

sysRefundList.dealWithMessage = function(apprResult){
    if (apprResult.result == "SUCCESS") {
        window.top.window.showScoMessage('ok', "审核成功");
        sysRefundList.queryTableData();
    } else if (apprResult.result == "FAILED") {
        var showingMessage = "退款单[" + apprResult.sysRefundCode + "]审核失败,原因：";
        for (var i=0,j=apprResult.detail.length;i<j;i++) {
            var detailItem = apprResult.detail[i];
            if (detailItem.result == "FAILED") {
                showingMessage += detailItem.message;
            }
        }
        window.top.window.showModalAlert(showingMessage);
    } else if(apprResult.result == "CONFIRM"){
        var showingMessage = "退款单[" + apprResult.sysRefundCode + "]检测到：";
        for (var i=0,j=apprResult.detail.length;i<j;i++) {
            var detailItem = apprResult.detail[i];
            if (detailItem.result == "CONFIRM") {
                showingMessage += detailItem.message;
            }
        }
        window.top.window.showModalConfirm(showingMessage + "是否通过审核?", function() {
            sysRefundList.operation.forceAuthen(apprResult.sysRefundId);
        });
    }
};

// 强制审核
sysRefundList.operation.forceAuthen = function(sysRefundIds) {
	var loading = window.top.window.getIndexBusyOverlay();
    $.ajax({
        type : "GET",
        url : "/sysRefundManager/forceApprSysRefund.action",
        contentType : "application/json;charset=utf-8",
        data : {
            "refundIds" : sysRefundIds
        },
        dataType : "json",
//        async : false,
        beforeSend:function(){
            if(loading) {
            	loading.settext("正在处理中，请稍后...");
            }
        },
        success : function(data) {
            if (data.result == "success") {
//                var item = data.message[0];
//                if (!!item.message) {
//                    // 是否创建退货单提示
//                    window.top.window.showModalConfirm(item.message, function() {
//                        sysRefundList.operation.createReturn(sysRefundIds);
//                    });
//                } else {
//                }
                window.top.window.showScoMessage('ok', data.msg);
                sysRefundList.queryTableData();
            } else {
                window.top.window.showModalAlert(data.msg);
            }
        },
        error : function(XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                window.top.window.showModalAlert(result.errorObject.errorText);
            }
        }
    });
};

// 根据退款单自动创建退货单
sysRefundList.operation.createReturn = function(sysRefundIds) {
	var loading = window.top.window.getIndexBusyOverlay();
    $.ajax({
        type : "GET",
        url : "/sysReturnManager/autoGenSysReturnBySysRefund.action",
        contentType : "application/json;charset=utf-8",
        data : {
            "refundIds" : sysRefundIds
        },
        dataType : "json",
//        async : false,
        beforeSend:function(){
            if(loading) {
            	loading.settext("正在处理中，请稍后...");
            }
        },
        success : function(data) {
            if (data.result == "success") {
                window.top.window.showScoMessage('ok', data.msg);
            } else {
                window.top.window.showModalAlert(data.msg);
            }
        },
        error : function(XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                window.top.window.showModalAlert(result.errorObject.errorText);
            }
        }
    });
}